import { defineStore } from 'pinia'
import { accountLogin, userInfoById, menuListByRoleId } from '../../api/login'
import { getCache, setCache } from '../../utils/cache'
import router from '@/router'


const userStore = defineStore('user', {
  state: () => ({
    name: '',
    token: '',
    userInfo: {},
    userMenus: []
  }),
  actions: {
    async login(userInfo) {
      // 1.获取token
      const loginRes = await accountLogin(userInfo)
      this.token = loginRes.data.token
      setCache('token', this.token)
      const id = loginRes.data.id
      // 2.获取用户信息
      this.getUserInfo(id)
    },
    async getUserInfo(id) {
      const userInfoRes = await userInfoById(id)
      this.userInfo = userInfoRes.data
      setCache('userInfo', this.userInfo)
      const roleId = userInfoRes.data.role.id
      // 3.获取菜单
      this.getMenuList(roleId)
    },
    async getMenuList(roleId) {
      const userMenuRes = await menuListByRoleId(roleId)
      this.userMenus = userMenuRes.data
      setCache('menuList', this.userMenus)

      // 4.跳到首页
      router.push('/main')
    },
     // 因为vuex里的数据是发送请求之后存的，刷新页面之后会清空
    // 初始化页面，如果有token，说明已经登录过了，直接跳转到首页，并且从缓存到拿到用户菜单数据
    loadLocalLogin() {
      const token = getCache('token')
      if (token) {
        this.token = token
      }
      const menuList = getCache('menuList')
      if (menuList) {
        this.menuList = menuList
      }
      const userInfo = getCache('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      }
    }
  }
})
export default userStore